package com.macro.mall.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dao.PortalOrderDao;
import com.macro.mall.domain.*;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.component.CancelOrderSender;
import com.macro.mall.portal.service.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 前台订单管理Service
 * Created by macro on 2018/8/30.
 */
@Service
@Log4j2
@Transactional
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private OmsCartItemService cartItemService;
    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;
    @Autowired
    private UmsMemberCouponService memberCouponService;
    @Autowired
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.orderId}")
    private String REDIS_KEY_PREFIX_ORDER_ID;
    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private CancelOrderSender cancelOrderSender;
    @Autowired
    private PmsProductService pmsProductService;
    @Autowired
    private SapAccountMapper sapAccountMapper;
    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;
    @Autowired
    private PmsProductService pmsProductServiceImpl;
    @Autowired
    private PmsProductMapper productMapper;

    @Override
    public ConfirmOrderResult generateConfirmOrder() {
        ConfirmOrderResult result = new ConfirmOrderResult();
        //获取购物车信息
        UmsMember currentMember = memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId());
        result.setCartPromotionItemList(cartPromotionItemList);
        //获取用户收货地址列表
        List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
        result.setCouponHistoryDetailList(couponHistoryDetailList);
        //获取用户积分
        result.setMemberIntegration(currentMember.getIntegration());
        //获取积分使用规则
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        result.setIntegrationConsumeSetting(integrationConsumeSetting);
        //计算总金额、活动优惠、应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
        result.setCalcAmount(calcAmount);
        return result;
    }

    @Override
    public CommonResult generateOrder(OrderParam orderParam) {
        // 获取购物车及优惠信息
        HashMap<String, Object> map = new HashMap<String, Object>();

        if (null == orderParam.getProductId()) {
            map.put("status", "1");
            map.put("desc", "订单编号不能为空！");
            return CommonResult.failed(map.toString());
        }
        PmsProduct pmsProduct = productMapper.selectByPrimaryKey(orderParam.getProductId());
        Integer stock = pmsProduct.getStock();
        Integer quantity = orderParam.getQuantity();
        if (stock - quantity <= 0) {
            map.put("status", "1");
            map.put("desc", "库存不足，无法下单");
            return CommonResult.failed(map.toString());
        }

        //生成下单商品信息
        OmsOrder order = new OmsOrder();
        order.setId(null);
        String orderSn = generateOrderSn(order);
        //生成订单号
        order.setOrderSn(orderSn);
        order.setMemberId(orderParam.getMemberId());
        order.setReceiverName(orderParam.getReceiverName());
        order.setReceiverPhone(orderParam.getReceiverPhone());
        order.setReceiverDetailAddress(orderParam.getReceiverDetailAddress());
//        order.setMemberUsername(currentMember.getUsername());
        BigDecimal multiply = orderParam.getOriginalPrice().multiply(new BigDecimal(quantity));
        BigDecimal add = multiply.add(orderParam.getFreightAmount());
        log.info("商品单价：{}，个数：{}，运费：{}，订单总价：{}", orderParam.getOriginalPrice(), quantity, orderParam.getFreightAmount(), add);
        order.setTotalAmount(add);
        order.setStatus(0);
        order.setCreateTime(new Date());
        order.setPayType(0);
        order.setConfirmStatus(0);
        BigDecimal multiply1 = orderParam.getOriginalPrice().subtract(pmsProduct.getPrice()).multiply(new BigDecimal(quantity));
        order.setProfitAmount(multiply1);
        //插入order表
        orderMapper.insertSelective(order);
        pmsProduct.setStock(stock - quantity);
        if (stock - quantity == 0) {
            pmsProduct.setPublishStatus(0);
        }
        OmsOrderItem omsOrderItem = new OmsOrderItem();
        omsOrderItem.setId(null);
        omsOrderItem.setOrderId(order.getId());
        omsOrderItem.setOrderSn(orderSn);
        omsOrderItem.setProductId(orderParam.getProductId());
        omsOrderItem.setProductPrice(orderParam.getOriginalPrice());
        omsOrderItem.setProductQuantity(quantity);
        omsOrderItem.setProfitAmount(multiply1);
        orderItemMapper.insertSelective(omsOrderItem);
        pmsProductServiceImpl.update(pmsProduct.getId(), pmsProduct);
        map.put("status", "0");
        map.put("orderId", order.getId());
        map.put("desc", "下单成功！");
        return CommonResult.success(map.toString());
    }

    @Override
    public CommonResult paySuccess(Long orderId) {
        //修改订单支付状态
        OmsOrder order = new OmsOrder();
        order.setId(orderId);
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
        omsOrder.setStatus(1);
        omsOrder.setPaymentTime(new Date());
        orderMapper.updateByPrimaryKeySelective(omsOrder);
        SapAccountExample sapAccount = new SapAccountExample();
        SapAccountExample.Criteria criteria = sapAccount.createCriteria();
        criteria.andMemberIdEqualTo(999L);
        List<SapAccount> sapAccounts = sapAccountMapper.selectByExample(sapAccount);
        if (null != sapAccounts && !sapAccounts.isEmpty() ) {
            SapAccount account = sapAccounts.get(0);
            BigDecimal waitIncomeAmount = account.getWaitIncomeAmount();
            log.info("waitIncomeAmount,{}", waitIncomeAmount);
            BigDecimal totalAmount = omsOrder.getTotalAmount();
            log.info("totalAmount,{}", totalAmount);
            account.setWaitIncomeAmount(waitIncomeAmount.add(totalAmount));
            account.setWaitIncomeProfit(account.getWaitIncomeAmount().add(omsOrder.getProfitAmount()));
            account.setAccountBalance(account.getAccountBalance().add(omsOrder.getTotalAmount()));
            sapAccountMapper.updateByPrimaryKeySelective(account);
        } else {
            SapAccount account = new SapAccount();
            account.setMemberId(999L);
            account.setAccountBalance(omsOrder.getTotalAmount());
            account.setFreezeAmount(new BigDecimal(0));
            account.setWaitIncomeAmount(new BigDecimal(0));
            account.setWaitIncomeProfit(new BigDecimal(0));
            account.setMemberName("后台账户");
            account.setId(null);
            sapAccountMapper.insertSelective(account);
        }
        return CommonResult.success("支付成功");
    }

    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private PmsProductMapper pmsProductMapper;

    @Override
    public CommonResult cancelTimeOutOrder() {
        OmsOrderExample omsOrderExample = new OmsOrderExample();
        OmsOrderExample.Criteria criteria = omsOrderExample.createCriteria();
        criteria.andStatusEqualTo(0);
        criteria.andCreateTimeLessThan(new Date(new Date().getTime() - 60 * 60 * 1000));
        List<OmsOrder> omsOrders = omsOrderMapper.selectByExample(omsOrderExample);
        if (CollectionUtils.isEmpty(omsOrders)) {
            return CommonResult.failed("暂无超时订单");
        }
        for (OmsOrder order : omsOrders) {
            Date createTime = order.getCreateTime();
            OmsOrderItemExample omsOrderItemExample = new OmsOrderItemExample();
            OmsOrderItemExample.Criteria criteria1 = omsOrderItemExample.createCriteria();
            criteria1.andOrderIdEqualTo(order.getId());
            List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(omsOrderItemExample);
            OmsOrderItem omsOrderItem = omsOrderItems.get(0);
            Integer productQuantity = omsOrderItem.getProductQuantity();
            PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(omsOrderItem.getProductId());
            Integer stock = pmsProduct.getStock();
            pmsProduct.setStock(stock + productQuantity);
            pmsProductMapper.updateByPrimaryKey(pmsProduct);
            order.setStatus(4);
            orderMapper.updateByPrimaryKeySelective(order);
        }
        return CommonResult.success(null);
    }

    @Override
    public void cancelOrder(Long orderId) {
        //查询为付款的取消订单
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andIdEqualTo(orderId);
//                .andStatusEqualTo(0)
//                .andDeleteStatusEqualTo(0);
        List<OmsOrder> cancelOrderList = orderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(cancelOrderList)) {
            return;
        }
        OmsOrder cancelOrder = cancelOrderList.get(0);
        if (cancelOrder != null) {
            //修改订单状态为取消
            cancelOrder.setStatus(4);
            orderMapper.updateByPrimaryKeySelective(cancelOrder);
            OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
            orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
            if (CollectionUtils.isEmpty(cancelOrderList)) {
                return;
            }
            for (OmsOrder order : cancelOrderList) {
                OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(order.getId());
                Integer productQuantity = omsOrderItem.getProductQuantity();
                PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(omsOrderItem.getProductId());
                Integer stock = pmsProduct.getStock();
                pmsProduct.setStock(stock + productQuantity);
                pmsProductMapper.updateByPrimaryKey(pmsProduct);
                order.setStatus(4);
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
    }

    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        cancelOrder(orderId);
//        //获取订单超时时间
//        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
//        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
//        //发送延迟消息
//        cancelOrderSender.sendMessage(orderId, delayTimes);
    }

    @Override
    public PageInfo<OmsOrder> getOrderList(OrderParam orderParam, Integer pageNum, Integer pageSize) {
        OmsOrderExample omsOrderExample = new OmsOrderExample();
        OmsOrderExample.Criteria criteria = omsOrderExample.createCriteria();
        omsOrderExample.setOrderByClause("create_time desc ");
        if (null != orderParam.getId()) {
            criteria.andIdEqualTo(orderParam.getId());
        }
        if (null != orderParam.getMemberId()) {
            criteria.andMemberIdEqualTo(orderParam.getMemberId());
        }
        if (null != orderParam.getProductId()) {
            criteria.andMemberIdEqualTo(orderParam.getMemberId());
        }
        if (null != orderParam.getStatus()) {
            criteria.andStatusEqualTo(orderParam.getStatus());
        }
        criteria.andDeleteStatusEqualTo(0);
        PageHelper.startPage(pageNum, pageSize);
        List<OmsOrder> omsOrders = orderMapper.selectByExample(omsOrderExample);
        PageInfo<OmsOrder> pageInfo = new PageInfo<>(omsOrders);
        return pageInfo;
    }


    @Override
    public List<OmsOrderItem> getOrderItemList(Long orderId) {
        OmsOrderItemExample omsOrderItemExample = new OmsOrderItemExample();
        OmsOrderItemExample.Criteria criteria = omsOrderItemExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<OmsOrderItem> omsOrderItems = omsOrderItemMapper.selectByExample(omsOrderItemExample);
        return omsOrderItems;
    }

    @Override
    public Object updateStatus(Long orderId, Integer status) {
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setId(orderId);
        omsOrder.setStatus(status);
        return omsOrderMapper.updateByPrimaryKeySelective(omsOrder);
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_KEY_PREFIX_ORDER_ID + date;
        Long increment = redisService.increment(key, 1);
        sb.append(date);
//        sb.append(String.format("%02d", order.getSourceType()));
//        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 删除下单商品的购物车信息
     */
    private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            ids.add(cartPromotionItem.getId());
        }
        cartItemService.delete(currentMember.getId(), ids);
    }

    /**
     * 计算该订单赠送的成长值
     */
    private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
        Integer sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算该订单赠送的积分
     */
    private Integer calcGifIntegration(List<OmsOrderItem> orderItemList) {
        int sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum += orderItem.getGiftIntegration() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 将优惠券信息更改为指定状态
     *
     * @param couponId  优惠券id
     * @param memberId  会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus) {
        if (couponId == null) return;
        //查询第一张优惠券
        SmsCouponHistoryExample example = new SmsCouponHistoryExample();
        example.createCriteria().andMemberIdEqualTo(memberId)
                .andCouponIdEqualTo(couponId).andUseStatusEqualTo(useStatus == 0 ? 1 : 0);
        List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(couponHistoryList)) {
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            couponHistory.setUseTime(new Date());
            couponHistory.setUseStatus(useStatus);
            couponHistoryMapper.updateByPrimaryKeySelective(couponHistory);
        }
    }

    private void handleRealAmount(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            //原价-促销价格-优惠券抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount())
                    .subtract(orderItem.getCouponAmount())
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(",");
        }
        String result = sb.toString();
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount());
        return payAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断是否可用
        //是否可与优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetail 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {
            //全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {
            //指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {
            //指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
            orderItem.setCouponAmount(couponAmount);
        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return result;
    }

    /**
     * 获取该用户可以使用的优惠券
     *
     * @param cartPromotionItemList 购物车优惠列表
     * @param couponId              使用优惠券id
     */
    private SmsCouponHistoryDetail getUseCoupon(List<CartPromotionItem> cartPromotionItemList, Long couponId) {
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
        for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
            if (couponHistoryDetail.getCoupon().getId().equals(couponId)) {
                return couponHistoryDetail;
            }
        }
        return null;
    }

    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 锁定下单商品的所有库存
     */
    private void lockStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId());
            skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
            skuStockMapper.updateByPrimaryKeySelective(skuStock);
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock() == null || cartPromotionItem.getRealStock() <= 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(new BigDecimal(0));
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
        return calcAmount;
    }

}
